package com.autoglm.android.core.accessibility

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Intent
import android.os.Build
import android.view.accessibility.AccessibilityEvent
import androidx.annotation.RequiresApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

/**
 * AutoGLM无障碍服务，用于接收系统无障碍事件
 */
class AutoGLMAccessibilityService : AccessibilityService() {
    // 协程作用域，用于异步处理
    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    
    // 当前活动窗口信息流
    private val _activeWindowInfo = MutableStateFlow<ActiveWindowInfo?>(null)
    val activeWindowInfo: StateFlow<ActiveWindowInfo?> = _activeWindowInfo.asStateFlow()
    
    // 屏幕分析器
    private lateinit var screenAnalyzer: ScreenAnalyzer
    
    override fun onCreate() {
        super.onCreate()
    }
    
    override fun onServiceConnected() {
        super.onServiceConnected()
        
        // 配置无障碍服务
        val info = AccessibilityServiceInfo().apply {
            // 监听的事件类型
            eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or
                    AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED or
                    AccessibilityEvent.TYPE_VIEW_CLICKED or
                    AccessibilityEvent.TYPE_VIEW_FOCUSED
            
            // 反馈类型
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            
            // 通知超时
            notificationTimeout = 100
            
            // 其他标志位
            flags = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS or
                    AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or
                    AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY
                    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                flags = flags or AccessibilityServiceInfo.FLAG_ENABLE_ACCESSIBILITY_VOLUME
            }
        }
        
        // 应用配置
        serviceInfo = info
        
        // 初始化屏幕分析器
        initializeScreenAnalyzer()
    }
    
    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        // 当窗口状态变化时更新活动窗口信息
        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            val packageName = event.packageName?.toString() ?: ""
            val className = event.className?.toString() ?: ""
            
            serviceScope.launch {
                updateActiveWindowInfo(packageName, className)
            }
        }
    }
    
    override fun onInterrupt() {
        // 服务中断，例如被用户禁用
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 清理资源
    }
    
    @RequiresApi(Build.VERSION_CODES.N)
    private fun initializeScreenAnalyzer() {
        val screenCaptureService = ScreenCaptureService(applicationContext)
        screenAnalyzer = ScreenAnalyzer(this, screenCaptureService)
    }
    
    private suspend fun updateActiveWindowInfo(packageName: String, className: String) {
        // 检查是否完整初始化，避免空指针
        if (!::screenAnalyzer.isInitialized) return
        
        // 分析当前屏幕
        val screenResult = screenAnalyzer.analyzeCurrentScreen()
        
        if (screenResult.success) {
            _activeWindowInfo.value = ActiveWindowInfo(
                packageName = packageName,
                className = className,
                timestamp = System.currentTimeMillis(),
                elementCount = screenResult.elements.size,
                activityName = screenResult.activityName,
                hasScreenshot = screenResult.screenshot != null
            )
        }
    }
    
    /**
     * 处理媒体投影权限结果
     */
    fun handleMediaProjectionResult(resultCode: Int, data: Intent) {
        if (!::screenAnalyzer.isInitialized) return
        
        val screenCaptureService = (screenAnalyzer as? ScreenAnalyzer)?.let {
            it.javaClass.getDeclaredField("screenCaptureService").apply {
                isAccessible = true
            }.get(it) as? ScreenCaptureService
        }
        
        screenCaptureService?.startCapture(resultCode, data)
    }
}

/**
 * 活动窗口信息数据类
 */
data class ActiveWindowInfo(
    val packageName: String,
    val className: String,
    val timestamp: Long,
    val elementCount: Int,
    val activityName: String? = null,
    val hasScreenshot: Boolean = false
) 